﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MarkdownPicture
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
        }
        /// <summary>
        /// 通过网址获取图片文件流
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private async Task<byte[]> GetImgByUrl(string url)
        {
            var handler = new HttpClientHandler();
            handler.AllowAutoRedirect = true;
            handler.UseCookies = true;
            handler.ClientCertificateOptions = ClientCertificateOption.Automatic;

            var client = new HttpClient(handler);
            return await client.GetByteArrayAsync(url).ConfigureAwait(false);
        }
        /// <summary>
        /// 根据图形获取图形的扩展名 zgke@sina.com qq:116149
        /// </summary>
        /// <param name="p_Image">图形</param>
        /// <returns>扩展名</returns>
        public string GetImageExtension(Image image)
        {
            Type Type = typeof(ImageFormat);
            System.Reflection.PropertyInfo[] _ImageFormatList = Type.GetProperties(BindingFlags.Static | BindingFlags.Public);
            for (int i = 0; i != _ImageFormatList.Length; i++)
            {
                ImageFormat _FormatClass = (ImageFormat)_ImageFormatList[i].GetValue(null, null);
                if (_FormatClass.Guid.Equals(image.RawFormat.Guid))
                {
                    return _ImageFormatList[i].Name;
                }
            }
            return "";
        }
        public void SetPicture(Image img, string ext, string base64String)
        {
            //pb.Size = new Size(bkImage.Width + 6, bkImage.Height + 33); //根据图片设置窗体的大小
            //pb.BackgroundImage = bkImage;//在窗体背景中显示图片
            PictureBox pictureBox = new PictureBox();
            pictureBox.Image = img;
            pictureBox.Size = new Size(160, 130);
            pictureBox.SizeMode = PictureBoxSizeMode.StretchImage;
            pictureBox.Dock = DockStyle.Left;
            TextBox textBox = new TextBox();
            textBox.Multiline = true;
            textBox.Size = new Size(130, 130);
            textBox.Dock = DockStyle.Fill;
            textBox.MaxLength = 9999999;
            textBox.Enter += TextBox_Enter;

            Panel panel = new Panel();
            panel.Dock = DockStyle.Top;
            panel.Size = new Size(160, 160);
            panel.Padding = new Padding(10);
            panel.Controls.Add(textBox);
            panel.Controls.Add(pictureBox);

            this.panel2.Controls.Add(panel);
            textBox.AppendText(base64String);
        }
        public void SetPicture(Image img,string ext)
        {
            //获取base64
            ImageConverter converter = new ImageConverter();
            byte[] data = (byte[])converter.ConvertTo(img, typeof(byte[]));
            string base64String = "data:image/" + ext + ";base64," + Convert.ToBase64String(data, 0, data.Length);

            SetPicture(img, ext, base64String);
        }
        public void SetPicture(byte[] bytes)
        {
            Image img = null;
            using (MemoryStream ms = new MemoryStream(bytes))
            {
                ms.Write(bytes, 0, bytes.Length);
                img = Image.FromStream(ms);
            }
            string ext = GetImageExtension(img);
            if (ext == "MemoryBmp")
            {
                ext = "jpg";
            }
            //获取base64
            string base64String = "data:image/" + ext + ";base64," + Convert.ToBase64String(bytes, 0, bytes.Length);
            SetPicture(img, ext, base64String);
        }
        /// <summary>
        /// 拖动图片到窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.All;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void label1_DragDrop(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Copy;//设置拖放操作中目标放置类型为复制
            string[] str_Drop = (string[])e.Data.GetData(DataFormats.FileDrop, true);//检索数据格式相管理的数据
            //string tempstr;

            //tempstr = str_Drop[0];//获取拖放文件的目录
            foreach (string tempstr in str_Drop)
            {
                Bitmap img = new Bitmap(tempstr);//存储拖放的图片
                string ext = Path.GetExtension(tempstr).Remove(0, 1);
                SetPicture(img, ext);
            }
        }
        /// <summary>
        /// 点击全选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TextBox_Enter(object sender, EventArgs e)
        {
            ((TextBox)sender).SelectAll();
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            StringCollection sc = Clipboard.GetFileDropList();
            if (sc.Count > 0)
            {
                for (int i = 0; i < sc.Count; i++)
                {
                    string tempstr = sc[i];
                    Bitmap img = new Bitmap(tempstr);//存储拖放的图片
                    string ext = Path.GetExtension(tempstr).Remove(0, 1);
                    SetPicture(img, ext);
                }
            }
            
            Image image = Clipboard.GetImage();
            if (image != null)
            {
                string ext = GetImageExtension(image);
                if (ext == "MemoryBmp")
                {
                    ext = "jpg";
                }
                SetPicture(image, ext);
            }
            string imgSrc= Clipboard.GetText();
            if (imgSrc != null && imgSrc.Contains("http"))
            {
                byte[] bytes = GetImgByUrl(imgSrc).Result;

                SetPicture(bytes);
            }
        }
        //浏览选择图片
        private void label1_DoubleClick(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件夹";
            dialog.Filter = "所有文件(*.*)|*.*";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string[] files = dialog.FileNames;
                foreach (string tempstr in files)
                {
                    Bitmap img = new Bitmap(tempstr);//存储拖放的图片
                    string ext = Path.GetExtension(tempstr).Remove(0, 1);
                    SetPicture(img, ext);
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.panel2.Controls.Clear();
        }
    }
}
